import java.util.concurrent.*;
import java.util.*;

public class ExArray {
    private static int[] intArray;


    //返回一个整型数组，数组中的元素是并行地随机产生的
    public static int[] randomIntArray(int size) {
        if (size < 0) throw new IllegalArgumentException("Array size less than zero.");
        intArray = new int[size];
        ForkJoinPool pool = new ForkJoinPool();
        FillRandomArrayTask masterTask = new FillRandomArrayTask(0, size);
        pool.invoke(masterTask);
        return intArray;
    }

    //用于实现randomIntArray方法的内部类
    static class FillRandomArrayTask extends RecursiveAction {
        private final int left;
        private final int right; //Task负责填充的范围是[left,right-1]
        private static final int THRESHOLD = 100;

        public FillRandomArrayTask(int left, int right) {
            this.left = left;
            this.right = right;
        }

        public void compute() {
            //问题规模足够小，串行解决
            if (right - left + 1 <= THRESHOLD) {
                Random r = new Random();
                for (int i = left; i <= right - 1; i++) {
                    intArray[i] = r.nextInt();
                }
            }
            else {
                int medium = (left + right) / 2;
                FillRandomArrayTask leftTask = new FillRandomArrayTask(left, medium);
                FillRandomArrayTask rightTask = new FillRandomArrayTask(medium, right);
                leftTask.invoke();
                rightTask.invoke();
            }
        }
    }
}
